const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const cache = require("apicache").middleware;

const father = express();
const vuepress = require("./applications/vuepress");
const xmiles = require("./applications/xmiles");
const reference = require("./applications/reference");

// CORS
father.use((req, res, next) => {
  if (req.path !== "/" && !req.path.includes(".")) {
    res.header({
      "Access-Control-Allow-Credentials": true,
      "Access-Control-Allow-Origin": req.headers.origin || "*",
      "Access-Control-Allow-Headers": "X-Requested-With",
      "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
      // "Content-Type": "application/json; charset=utf-8",
    });
  }
  next();
});

// cookie parser
father.use((req, res, next) => {
  (req.cookies = {}),
    (req.headers.cookie || "").split(/\s*;\s*/).forEach((pair) => {
      let crack = pair.indexOf("=");
      if (crack < 1 || crack == pair.length - 1) return;
      req.cookies[decodeURIComponent(pair.slice(0, crack)).trim()] =
        decodeURIComponent(pair.slice(crack + 1)).trim();
    });
  next();
});

// body parser
father.use(bodyParser.json());
father.use(bodyParser.urlencoded({ extended: false }));

// cache
father.use(cache("2 minutes", (req, res) => res.statusCode === 200));

// static
father.use(express.static(path.join(__dirname, "public")));

const port = process.env.PORT || 8995;

// 子应用
father.use("/vuepress", vuepress);
father.use("/xmiles", xmiles);
father.use("/reference", reference);

father.listen(port, () => {
  console.log(`server running @ http://localhost:${port}`);
});
